package com.ysu.yybk.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.ysu.yybk.entity.course.CourseStudent;
import com.ysu.yybk.entity.member.Student;
import com.ysu.yybk.enums.ResultEnum;
import com.ysu.yybk.exception.YybkException;
import com.ysu.yybk.mapper.course.CourseStudentMapper;
import com.ysu.yybk.mapper.member.StudentMapper;
import com.ysu.yybk.service.CourseService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class CourseServiceImpl implements CourseService {

    @Autowired
    private CourseStudentMapper courseStudentMapper;

    @Autowired
    private StudentMapper studentMapper;

    @Override
    public void addStudent(String studentId, String courseId) {
        // 查询学生是否存在
        Student student = studentMapper.selectById(studentId);
        if (student == null) {
            throw new YybkException(ResultEnum.STUDENT_NOT_EXIST);
        }
        // 判断学生是否在课程里
        LambdaQueryWrapper<CourseStudent> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(CourseStudent::getCourseId, courseId).eq(CourseStudent::getStudentId, studentId);
        Integer count = courseStudentMapper.selectCount(wrapper);
        if (count == 1) {
            throw new YybkException(ResultEnum.STUDENT_HAS_EXIST);
        }
        // 插入学生
        CourseStudent courseStudent = new CourseStudent();
        courseStudent.setCourseId(courseId);
        courseStudent.setStudentId(studentId);
        int insertCount = courseStudentMapper.insert(courseStudent);
        if (insertCount != 1) {
            throw new YybkException(ResultEnum.INSERT_FAIL);
        }
    }

    @Override
    public void deleteStudent(String studentId, String courseId) {
        // 查询学生是否存在
        Student student = studentMapper.selectById(studentId);
        if (student == null) {
            throw new YybkException(ResultEnum.STUDENT_NOT_EXIST);
        }
        // 判断学生是否在课程里
        LambdaQueryWrapper<CourseStudent> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(CourseStudent::getCourseId, courseId).eq(CourseStudent::getStudentId, studentId);
        Integer count = courseStudentMapper.selectCount(wrapper);
        if (count != 1) {
            throw new YybkException(ResultEnum.STUDENT_HAS_NOT_EXIST);
        }
        // 删除学生
        int deleteCount = courseStudentMapper.delete(wrapper);
        if (deleteCount != 1) {
            throw new YybkException(ResultEnum.INSERT_FAIL);
        }
    }
}
